<template>
  <el-form ref="ruleFormRef" class="demo-ruleForm" status-icon>
    <el-form-item label="文章标题" prop="title">
      <el-input
        v-model="formData.title"
        placeholder="请输入文章标题"
        size="large"
      />
    </el-form-item>
    <!-- 文章分类 -->
    <el-form-item label="文章分类" prop="category">
      <el-select
        v-model="formData.category"
        multiple
        collapse-tags
        collapse-tags-tooltip
        :max-collapse-tags="3"
        size="large"
        placeholder="请选择文章分类"
      >
        <el-option label="前端开发" value="前端开发" />
        <el-option label="后端开发" value="后端开发" />
        <el-option label="数据库" value="数据库" />
      </el-select>
    </el-form-item>
    <!-- 文章标签 -->
    <el-form-item label="文章标签" prop="tags">
      <el-tag
        v-for="tag in formData.tags"
        closable
        :key="tag"
        @close="handleClose(tag)"
      >
        {{ tag }}
      </el-tag>
      <el-input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        class="ml-1 w-20"
        size="small"
        @keyup.enter="handleInputConfirm"
        @blur="handleInputConfirm"
      />
      <el-button
        v-else
        class="button-new-tag ml-1"
        size="small"
        @click="showInput"
      >
        + 添加文章标签
      </el-button>
    </el-form-item>
    <!-- 文章显示或隐藏 -->
    <el-form-item label="显示或隐藏" prop="status">
      <el-switch
        v-model="deletedValue"
        inline-prompt
        active-text="显示"
        inactive-text="隐藏"
      />
    </el-form-item>
    <!-- 封面图片 -->
    <el-form-item label="封面图片" prop="cover">
      <el-upload
        action="#"
        list-type="picture-card"
        :auto-upload="false"
        :on-change="uploadSuccess"
      >
        <el-icon>
          <Plus />
        </el-icon>

        <template #file="{ file }">
          <div>
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <el-icon><zoom-in /></el-icon>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
              >
                <el-icon>
                  <Download />
                </el-icon>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <el-icon>
                  <Delete />
                </el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>
    </el-form-item>
    <!-- summary -->
    <el-form-item label="文章摘要" prop="summary">
      <el-input
        v-model="formData.summary"
        placeholder="请输入文章摘要"
        size="large"
        type="textarea"
        :rows="3"
        :maxlength="maxLength"
        show-word-limit
        clearable
      />
    </el-form-item>
    <el-form-item label="文章内容" prop="content">
      <!-- 富文本编辑器 -->
      <div class="editor-wrapper">
        <Toolbar
          style="border-bottom: 1px solid #ccc; width: 100%"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
        />
        <Editor
          style="height: 500px; overflow-y: hidden; width: 100%"
          v-model="formData.content"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </div>
    </el-form-item>
    <el-form-item class="form-but">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <!-- <el-button @click="handleCancel">取消</el-button> -->
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import {
  ref,
  shallowRef,
  onBeforeUnmount,
  nextTick,
  defineProps,
  watch,
  withDefaults,
  defineEmits,
  onMounted,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import type { UploadFile, UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import { postAddArticle, postUpdateArticle } from "../api/index";
import { ElInput } from "element-plus";
import { IEditorConfig } from "@wangeditor/editor";
//路由
import { useRouter } from "vue-router";
const router = useRouter();

/**
     * 表单数据类型
     * @interface FormData
     * @property {string} title - 文章标题
     * @property {string} category - 文章分类
     * @property {string} content - 文章内容
     * @property {string} summary - 文章摘要
     * @property {string} cover_image - 封面图片
     * @property {string[]} tags - 文章标签
     * @property {string} deleted - 文章状态
     * @property {string} publish_time - 发布时间
     * @property {string} created_at - 创建时间
     * @property {string} updated_at - 更新时间
     * @property {string} deleted_at - 删除时间
     * @property {string} id - 文章ID
     * @property {string} user_id - 用户ID
    
     */
interface FormData {
  title: string;
  category: string;
  content: string;
  summary: string;
  cover_image: string;
  tags: string[];
  deleted: Number;
}
/**
 * 默认封面图片
 */
const defaultCoverImage = ref(
  "https://pics4.baidu.com/feed/4e4a20a4462309f79a90717b627635ffd6cad664.jpeg@f_auto?token=7a3b13ee53076d0825bf3ec1f1e838d1"
);

// 表单数据
const formData = ref<FormData>({
  deleted: 0,
  title: "",
  category: "",
  content: "",
  summary: "",
  cover_image: "",
  tags: [],
});
const maxLength = ref<number>(200);
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
const deletedValue = ref<boolean>(true);

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);

// 使用 defineProps 定义 props
const props = withDefaults(
  defineProps<{
    FormArticle?: FormData; // 明确类型
    isDrawerOpenVule?: boolean; // 明确类型
  }>(),
  {
    isDrawerOpenVule: false, // 设置默认值为 false
  }
);

const handleRemove = (file: UploadFile) => {
  console.log(file);
};

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;

  dialogVisible.value = true;
};

const handleDownload = (file: UploadFile) => {
  console.log(file);
};
// 文件变化处理
const uploadSuccess: UploadProps["onChange"] = (file) => {
  // 生成本地预览URL
  if (file.status === "ready") {
    console.log(file);
    const url = URL.createObjectURL(file.raw!);
    console.log(url);
    formData.value.cover_image = url;
  }
};
//判断是否是josn
const isJsonString = (str: string): boolean => {
  try {
    JSON.parse(str); // 尝试解析字符串
    return true; // 解析成功，是 JSON 字符串
  } catch (e) {
    return false; // 解析失败，不是 JSON 字符串
  }
};
// 监听
watch(
  () => props.FormArticle,
  (newArticle) => {
    // 处理 props.article 的变化
    if (newArticle) {
      formData.value = {
        ...formData.value, // 保留默认值
        ...newArticle, // 覆盖为父组件传递的值
      };
      if (isJsonString(newArticle.category)) {
        formData.value.category = JSON.parse(newArticle.category);
      } else {
        console.log(
          formData.value.category,
          "-----------formData.value.category"
        );
      }
    }
  },
  { immediate: true }
);
// 移除标签
const handleClose = (tag: string) => {
  formData.value.tags.splice(formData.value.tags.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (
    inputValue.value &&
    formData.value.tags.indexOf(inputValue.value) === -1
  ) {
     formData.value.tags.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};
/**
 * 文章编辑器
 **/
interface IEditorConfig {
  placeholder?: string;
  MENU_CONF?: Record<string, any>;
}
// 编辑器模式
const mode = "default";

const imageUrl = ref("");
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 编辑器工具栏配置
const toolbarConfig = {};
const customHtmlFilter = (html: string): string => {
  // 1. 修复代码块被<p>标签分割的问题
  let cleanedHtml = html;
  // .replace(/<p>```(\w+?)<\/p>/g, '<pre><code class="language-$1">') // 修复代码块开始标记
  // .replace(/<p>```<\/p>/g, '</code></pre>')
  // 移除所有 <br> 标签
  // .replace(/<br\s*?\/?>/g, '')
  // 移除所有 <p> 和 </p> 标签（保留内容）
  // .replace(/<p>(.*?)<\/p>/g, '$1\n')
  // 移除空的 <p> 标签
  // .replace(/<p>\s*<\/p>/g, '')
  // 移除多余的 <pre><code> 标签对（保留内容）
  // .replace(/<pre><code\s*>/gi, '')
  // .replace(/<\/code>\s*<\/pre>/gi, '')
  // 修复代码块结束标记
  // .replace(/<p>(.*?)<\/p>/g, (match, content) => {
  //     // 在代码块内，将<p>内容</p>转换为行内容 + 换行
  //     if (match.startsWith('<p>') && match.endsWith('</p>') &&
  //         content.includes('<code') && content.includes('</code>')) {
  //         return content + '\n';
  //     }
  //     return match;
  // });

  // 2. 清理多余的HTML标签
  // cleanedHtml = cleanedHtml
  //     .replace(/<pre><code\s*>\s*<html\s[^>]*>/gi, '')
  //     .replace(/<\/html>\s*<\/code><\/pre>/gi, '')
  //     .replace(/<html\s[^>]*>/gi, '')
  //     .replace(/<\/html>/gi, '');

  // 3. 清理多余的换行和空格
  // cleanedHtml = cleanedHtml
  //     .replace(/\n{3,}/g, '\n\n') // 多个换行缩减为两个
  //     .replace(/\s{2,}/g, ' ');   // 多个空格缩减为一个

  // 4. 处理代码块内部的换行问题
  // cleanedHtml = cleanedHtml.replace(/<pre><code[^>]*>([\s\S]*?)<\/code><\/pre>/g,
  //     (match, codeContent) => {
  //         // 替换代码块内<br>为真实换行符
  //         codeContent = codeContent.replace(/<br\s?\/?>/gi, '\n');
  //         // 移除代码块内多余的段落标签
  //         codeContent = codeContent.replace(/<p>/gi, '').replace(/<\/p>/gi, '\n');
  //         return `<pre><code>${codeContent.trim()}</code></pre>`;
  //     }
  // );

  return cleanedHtml;
};

const editorConfig: Partial<IEditorConfig> = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    codeSelectLang: {
      codeLangs: [
        { text: "CSS", value: "css" },
        { text: "HTML", value: "html" },
        { text: "XML", value: "xml" },
        { text: "JavaScript", value: "javascript" },
        { text: "TypeScript", value: "typescript" },
        { text: "JSON", value: "json" },
        { text: "Java", value: "java" },
        { text: "Python", value: "python" },
        { text: "Bash", value: "bash" },
        { text: "SQL", value: "sql" },
        { text: "Markdown", value: "markdown" },
        { text: "Plain Text", value: "plaintext" },
        { text: "TypeScript React", value: "tsx" },
        { text: "Vue", value: "vue" },
        { text: "JSX", value: "jsx" },
      ],
      defaultLang: "html",
      formatLang: (lang: string) => `Language: ${lang}`,
    },
    uploadImage: {
      base64LimitSize: 5 * 1024, // 5KB 大小限制
    },
    insertLink: {
      // 配置点击链接行为
      onClick: (elem: any, editor: any) => {
        const href = elem?.href || "";
        window.open(href, "_blank");
      },
    },
  },
};

// 组件销毁时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor) editor.destroy();
});

// 记录 editor 实例 - 增强处理
const handleCreated = (editor: any) => {
  editorRef.value = editor;
  // 重写setHtml方法：自动应用过滤器
  const originalSetHtml = editor.setHtml.bind(editor);
  editor.setHtml = (html: string) => {
    originalSetHtml(customHtmlFilter(html));
  };

  // 添加代码块自动格式化规则
  editor.on("change", () => {
    const content = editor.getHtml();
    // 自动识别代码块
    const regex = /<p>```(\w+?)<\/p>([\s\S]*?)<p>```<\/p>/g;
    if (regex.test(content)) {
      const cleanedContent = customHtmlFilter(content);
      if (cleanedContent !== content) {
        editor.setHtml(cleanedContent);
      }
    }
  });
};

// 表单验证
const validateForm = (): boolean => {
  // 验证表单数据
  console.log(formData.value);
  if (!formData.value.title.trim()) {
    ElMessage.error("标题不能为空");
    return false;
  }
  if (!formData.value.category.length) {
    ElMessage.error("分类不能为空");
    return false;
  }
  if (!formData.value.content.trim()) {
    ElMessage.error("内容不能为空");
    return false;
  }
  if (!formData.value.summary.trim()) {
    ElMessage.error("摘要不能为空");
    return false;
  }
  if (formData.value.tags.length === 0) {
    ElMessage.error("至少需要一个标签");
    return false;
  }
  return true;
};
const getRandomInt = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
};
const stringToArray = (str, options = {}) => {
  // 合并默认选项
  const { trim = true, filterEmpty = true } = options;
  // 处理空值情况
  if (typeof str !== "string" || !str.trim()) {
    return [];
  }
  // 分割字符串（支持中英文逗号）
  const result = str.split(/[，,]/);
  // 处理元素
  return result
    .map((item) => (trim ? item.trim() : item)) // 可选：去除两端空格
    .filter((item) => !filterEmpty || item !== ""); // 可选：过滤空元素
};
// 保存操作
const handleSave = () => {
  // 确保编辑器内容已应用过滤器
  if (editorRef.value) {
    formData.value.content = customHtmlFilter(editorRef.value.getHtml());
  }

  if (!validateForm()) return;

  // 处理内容中的代码块特殊符号
  formData.value.content = formData.value.content
    .replace(/&amp;lt;/g, "<")
    .replace(/&amp;gt;/g, ">");
  try {
    if (!imageUrl.value) {
      // imageUrl.value = formData.value.cover_image || defaultCoverImage.value
      imageUrl.value = `https://picsum.photos/600/400?random=${getRandomInt(
        1,
        999
      )}`;
    }
    if (deletedValue.value) {
      formData.value.deleted = 0;
    } else {
      formData.value.deleted = 1;
    }
    if (Array.isArray(formData.value.category)) {
      formData.value.category = formData.value.category.join("，");
    }
    !props.isDrawerOpenVule ? saveArticle() : handleUpdate();
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败，请重试");
  }
  // 这里可以添加保存逻辑，例如调用 API 保存数据
};
// 保存文章接口
const saveArticle = async () => {
  const result = await postAddArticle({
    ...formData.value,
    cover_image: imageUrl.value,
  });
  if (result?.code === 0) {
    await ElMessage.success(result.msg);
    router.push("/home/article");
  }
};
// 文章修改
const handleUpdate = async () => {
  const result = await postUpdateArticle({
    ...formData.value,
    cover_image: imageUrl.value,
  });
  if (result.code === 0) {
    ElMessage.success(result.msg);
    router.go(0);
  }
};
// 取消操作
const handleCancel = () => {
  console.log("取消编辑");
  // 这里可以添加取消逻辑，例如清空表单或返回上一页
};
</script>

<style scoped lang="less">
.editor-wrapper {
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  padding: 10px;
  width: 100%;
}

.demo-ruleForm {
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  margin-right: 10px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-tag {
  margin: 0 8px;
}

.w-20 {
  width: 5rem;
}

.form-but {
  text-align: right;

  :deep(.el-form-item__content) {
    display: inline;
  }
}
</style>